package com.eliota.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eliota.common.Constants;
import com.eliota.common.R;
import com.eliota.controller.dto.ProjectDto;
import com.eliota.controller.dto.UserDto;
import com.eliota.entity.Project;
import com.eliota.entity.ProjectUser;
import com.eliota.entity.User;
import com.eliota.mapper.ProjectUserMapper;
import com.eliota.mapper.UserMapper;
import com.eliota.service.ProjectService;
import com.eliota.service.ProjectUserService;
import com.eliota.service.TypeService;
import com.eliota.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MG
 * @since 2023-04-01
 */
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Resource
    private ProjectService projectService;


    @Resource
    private TypeService typeService;

    @Resource
    private UserService userService;

    @Resource
    private ProjectUserService projectUserService;

    @PostMapping("/save")
    public R saveProject(@RequestBody Project project){
        /*projectService.saveWithUser(project);*/
        return R.success(projectService.saveOrUpdate(project));
    }

    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize,
                      @RequestParam String  projectName){
        /*Page<Project> projectPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        projectQueryWrapper.like("id",id).orderByDesc("id");
        projectQueryWrapper.eq("is_del",0);

        List<Map<String, Object>> maps = projectUserMapper.selectProjectByUserId(1);*/
        /*User currentUser = TokenUtil.getCurrentUser();*/
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + projectName);
        return R.success(projectService.findPage(new Page<>(pageNum,pageSize),projectName));
    }


    /*userNam*/
    @GetMapping("/project/{id}")
    public R findByUserName(@PathVariable Integer id){
        Project getProjectById = projectService.getOne(new QueryWrapper<Project>().eq("id", id));
        return R.success(getProjectById);
    }


    @DeleteMapping("/{projectId}")
    public R delete(@PathVariable Integer projectId){
        projectService.statusChange(projectId);
        return R.success();
    }

    @PostMapping("/bath/del")
    public R deleteBath(@RequestBody List<Integer> ids){
        projectService.deleteBatchByIds(ids);
        return R.success();
    }



    @GetMapping("/type/list")
    public R findTypes(){
        return R.success(typeService.list());
    }

    @GetMapping("/user/list")
    public R findUsers(){
        return R.success(userService.list());
    }


    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<ProjectUser> list = projectUserService.list();
        // 通过工具类创建writer 写出到磁盘路径
        //        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名

        writer.addHeaderAlias("projectId", "工程id");
        writer.addHeaderAlias("projectNum", "工程编号");
        writer.addHeaderAlias("projectName", "工程名");
        writer.addHeaderAlias("projectDesc", "工程描述");
        writer.addHeaderAlias("typeId", "工程类型");
        writer.addHeaderAlias("userId", "用户id");
        writer.addHeaderAlias("userName", "用户名");
        writer.addHeaderAlias("email", "邮箱");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public R imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<ProjectUser> projectUsers = CollUtil.newArrayList();
        for (List<Object> row : list) {
            ProjectUser projectUser = new ProjectUser();
            projectUser.setUserId(Integer.valueOf(row.get(0).toString()));
            projectUser.setUserId(Integer.valueOf(row.get(1).toString()));
            projectUser.setProjectId(Integer.valueOf(row.get(2).toString()));
            projectUsers.add(projectUser);
            System.out.println(projectUsers.toString());
        }

        projectUserService.saveBatch(projectUsers);
        return R.success(true);
    }



}
